import styles from "./index.module.less"
import { make } from "../../utils/dom"
import { v4 as uuid } from "uuid"
import mittBus from "@/utils/mitt"

class LineViewTool {
	static get isInline() {
		return true
	}

	static get CSS() {
		return styles["cdx-line-view"]
	}

	get toolboxIcon() {
		return `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="currentColor" d="M9 22a1 1 0 0 1-1-1v-3H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6.1l-3.7 3.71c-.2.19-.45.29-.7.29zm1-6v3.08L13.08 16H20V4H4v12zm7-5h-2V9h2zm-4 0h-2V9h2zm-4 0H7V9h2z"/></svg>`
	}

	static get sanitize() {
		return {
			p: {
				class: LineViewTool.CSS,
			},
		}
	}

	static get title() {
		return "划词评论"
	}
	// 当清除内敛样式时触发的行为(默认行为)
	clear() {}

	get state() {
		return this._state
	}

	set state(state) {
		this._state = state

		this.button.classList.toggle(this.api.styles.inlineToolButtonActive, state)
	}

	constructor({ api }) {
		this.api = api
		this.button = null
		this._state = false
		// 注意: 如果当前标签和已有内敛工具重合, 则会造成同时选中的问题, 所以每个内敛工具标签需要有自己的标签
		this.tag = "P"
	}

	render() {
		this.button = make("button", styles["line-view"], { type: "button" })
		this.button.innerHTML = this.toolboxIcon
		this.button.classList.add(this.api.styles.inlineToolButton)

		return this.button
	}

	// 应用插件时执行此方法
	surround(range) {
		if (!range) {
			return
		}

		// if (this.state) {
		//     this.unwrap(range);
		//     return;
		// }
		this.wrap(range)
	}

	wrap(range) {
		// 判断选中的文本是否和已有的标签重合
		const hasmark = this.api.selection.findParentTag(this.tag, LineViewTool.CSS)
		if (hasmark) {
			const note = hasmark.querySelector(".fm-note")
			note && note.remove()
		}
		const selectedText = range.extractContents()
		const text = selectedText.textContent

		let id = hasmark ? hasmark.id : "fm_" + uuid()

		const mark = make(this.tag, [LineViewTool.CSS, id], { id: id })

		mark.appendChild(selectedText)
		range.insertNode(mark)

		this.api.selection.expandToTag(mark)

		// 触发事件, 通知父组件添加评论
		mittBus.emit("addReview", { id, text })
	}

	unwrap(range) {
		// const mark = this.api.selection.findParentTag(this.tag);
		// const text = range.extractContents();
		// mark.remove();
		// range.insertNode(text);
	}

	// 点击按钮, 选中文本时执行此方法(默认行为)
	checkState(selection) {
		// const mark = this.api.selection.findParentTag(this.tag, LineViewTool.CSS);
		// 查找当前标签是否有子元素fm-note
		// const note = mark.querySelector('.fm-note');
		// this.state = !!mark;
		// console.log(22, mark, note)
	}
	// 选中文本时执行此方法(默认行为)
	// renderActions() {
	//     this.emptyEl = make('span');

	//     return this.emptyEl
	// }
}

export default LineViewTool

